<template>
  <view class="comment-detail-page" :style="{'--primary-color': primaryColor}">
    <!-- 评价详情卡片 -->
    <view class="comment-card" v-if="commentDetail">
      <!-- 评价头部 -->
      <view class="comment-header">
        <view class="user-info">
          <text class="username">{{ commentDetail.userName }}</text>
          <view class="rating">
            <text 
              class="star" 
              :class="{ 'active': index <= commentDetail.rating }"
              v-for="index in 5" 
              :key="index"
            >★</text>
          </view>
        </view>
        <text class="comment-time">{{ commentDetail.createTime }}</text>
      </view>
      
      <!-- 评价内容 -->
      <view class="comment-content">
        <text class="comment-text">{{ commentDetail.content }}</text>
      </view>
      
      <!-- 评价图片 -->
      <view class="comment-images" v-if="commentDetail.images && commentDetail.images.length > 0">
        <image 
          class="comment-image" 
          v-for="(image, index) in commentDetail.images" 
          :key="index"
          :src="image"
          mode="aspectFill"
          @click="previewImage(commentDetail.images, index)"
        />
      </view>
      
      <!-- 商户回复 -->
      <view class="merchant-reply" v-if="commentDetail.merchantReply">
        <view class="reply-header">
          <text class="reply-label">商户回复</text>
        </view>
        <text class="reply-content">{{ commentDetail.merchantReply }}</text>
      </view>
    </view>
    
    <!-- 相关商品信息 -->
    <view class="product-card" v-if="commentDetail && commentDetail.productInfo">
      <view class="card-header">
        <text class="card-title">相关商品</text>
      </view>
      <view class="product-info" @click="goToProduct">
        <image class="product-image" :src="commentDetail.productInfo.image" mode="aspectFill" />
        <view class="product-details">
          <text class="product-name">{{ commentDetail.productInfo.name }}</text>
          <text class="product-price">¥{{ commentDetail.productInfo.price }}</text>
        </view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && !commentDetail">
      <text class="empty-text">评价不存在或已被删除</text>
    </view>
  </view>
</template>

<script>
import { getCommentDetail } from '@/api/comment'
import { API_CONFIG } from '@/config/api'
import browseTracker from '@/utils/browseTracker'
import { getToken, getUserInfo } from '@/utils/auth'
import { getThemePrimaryColor, getThemeColorFromGlobal } from '@/utils/theme'

export default {
  data() {
    return {
      commentId: '',
      productId: '',
      commentDetail: null,
      loading: false,
      themeColor: '1' // 主题色编号
    }
  },
  
  computed: {
    // 动态获取主题色
    primaryColor() {
      return getThemePrimaryColor(this.themeColor)
    },
    // 主题色样式
    themeColorStyles() {
      const styles = this.setThemeColorVariables(this.primaryColor)
      return {
        '--primary-color': styles.primaryColor,
        '--primary-color-light': styles.primaryColorLight,
        '--primary-color-glow': styles.primaryColorGlow,
        '--primary-color-shadow': styles.primaryColorShadow,
        '--background-gradient': styles.backgroundGradient,
        '--card-shadow': styles.cardShadow,
        '--card-border': styles.cardBorder,
        '--reply-border-color': styles.replyBorderColor
      }
    }
  },
  
  onLoad(options) {
    this.initThemeColor()
    this.commentId = options.commentId || ''
    this.productId = options.productId || ''
    
    // 检查参数是否有效
    if (!this.commentId || this.commentId === 'undefined') {
      uni.showToast({
        title: '评价信息错误',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    if (!this.productId || this.productId === 'undefined') {
      uni.showToast({
        title: '商品信息错误',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    this.initThemeColor()
    this.loadCommentDetail()
    this.startBrowseTracking()
  },
  
  onShow() {
    browseTracker.resume()
  },
  
  onHide() {
    browseTracker.pause()
  },
  
  onUnload() {
    browseTracker.stopTracking()
  },
  
  beforeDestroy() {
    browseTracker.stopTracking()
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 加载评价详情
    async loadCommentDetail() {
      if (!this.commentId) {
        this.$modal.showToast('评价ID不能为空')
        return
      }
      
      this.loading = true
      
      try {
        // 首先尝试从商品评价缓存中获取
        const productCacheKey = `comment_detail_${this.productId}`
        const productComments = uni.getStorageSync(productCacheKey)
        if (productComments && Array.isArray(productComments)) {
          const foundComment = productComments.find(comment => 
            (comment.comment_id || comment.commentId || comment.id) == this.commentId
          )
          if (foundComment) {
            console.log('从商品评价缓存获取评价详情:', foundComment)
            // 转换字段名称
            this.commentDetail = {
              id: foundComment.comment_id || foundComment.commentId || foundComment.id,
              productId: foundComment.product_id || foundComment.productId,
              orderId: foundComment.order_id || foundComment.orderId,
              userId: foundComment.user_id || foundComment.userId,
              userName: foundComment.user_name || foundComment.userName || '匿名用户',
              userAvatar: foundComment.user_avatar || foundComment.userAvatar || '/static/images/default-avatar.png',
              rating: foundComment.star || 5,
              star: foundComment.star || 5,
              content: foundComment.content || '',
              images: this.processImages(foundComment.images),
              merchantReply: foundComment.reply_content || foundComment.replyContent || foundComment.merchantReply,
              replyTime: foundComment.reply_time || foundComment.replyTime,
              showStatus: foundComment.show_status || foundComment.showStatus,
              createTime: this.formatTime(foundComment.create_time || foundComment.createTime),
              updateTime: foundComment.update_time || foundComment.updateTime,
              product: foundComment.product || {}
            }
            this.loading = false
            return
          }
        }
        
        // 尝试从单个评价缓存获取
        const cacheKey = `comment_detail_${this.commentId}`
        const cachedData = uni.getStorageSync(cacheKey)
        if (cachedData) {
          this.commentDetail = cachedData
          this.loading = false
          return
        }
        
        const response = await getCommentDetail({
          commentId: this.commentId,
          productId: this.productId
        })
        
        if (response.code === 200) {
          // 转换字段名称（数据库下划线命名转为前端驼峰命名）
          const data = response.data
          this.commentDetail = {
            id: data.comment_id || data.commentId || data.id,
            productId: data.product_id || data.productId,
            orderId: data.order_id || data.orderId,
            userId: data.user_id || data.userId,
            userName: data.user_name || data.userName || '匿名用户',
            userAvatar: data.user_avatar || data.userAvatar || '/static/images/default-avatar.png',
            rating: data.star || 5,
            star: data.star || 5,
            content: data.content || '',
            images: this.processImages(data.images),
            merchantReply: data.reply_content || data.replyContent || data.merchantReply,
            replyTime: data.reply_time || data.replyTime,
            showStatus: data.show_status || data.showStatus,
            createTime: this.formatTime(data.create_time || data.createTime),
            updateTime: data.update_time || data.updateTime,
            product: data.product || {}
          }
          
          // 缓存数据
          uni.setStorageSync(cacheKey, this.commentDetail)
        } else {
          this.$modal.showToast(response.msg || '获取评价详情失败')
        }
      } catch (error) {
        console.error('获取评价详情失败:', error)
        this.$modal.showToast('网络错误，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        current: current,
        urls: images
      })
    },
    
    // 跳转到商品详情
    goToProduct() {
      if (this.productId) {
        uni.navigateTo({
          url: `/pages/product/detail?id=${this.productId}`
        })
      }
    },
    
    // 处理图片数据
    processImages(images) {
      if (!images) return []
      
      let imageList = []
      if (Array.isArray(images)) {
        imageList = images
      } else if (typeof images === 'string') {
        imageList = images.split(',').filter(img => img.trim())
      } else {
        return []
      }
      
      // 处理图片URL，确保是完整的URL
      return imageList.map(image => {
        return this.processImageUrl(image)
      }).filter(url => url)
    },
    
    // 处理图片URL
    processImageUrl(imagePath) {
      if (!imagePath) return ''
      
      // 如果已经是完整的URL，直接返回
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath
      }
      
      // 处理服务器路径
      let serverUrl = API_CONFIG.SERVER_IP
      
      // 如果包含/dev-api，替换成/
      if (imagePath.includes('/dev-api')) {
        imagePath = imagePath.replace('/dev-api', '')
      }
      
      // 确保路径以/开头
      if (!imagePath.startsWith('/')) {
        imagePath = '/' + imagePath
      }
      
      return serverUrl + imagePath
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      if (isNaN(date.getTime())) return time
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    // 初始化主题色
    async initThemeColor() {
      try {
        // 获取主题色配置
        const themeColor = await getThemeColorFromGlobal()
        
        // 判断是否为异步主题色（数字字符串表示需要从服务器获取）
        if (/^\d+$/.test(themeColor)) {
          // 异步获取主题色
          this.themeColor = themeColor
          console.log('异步获取主题色 - 评论详情页面:', themeColor)
        } else {
          // 同步获取主题色（直接使用颜色值）
          this.themeColor = themeColor
          console.log('同步获取主题色 - 评论详情页面:', themeColor)
        }
      } catch (error) {
        console.error('评论详情页面主题色初始化失败:', error)
        // 使用默认主题色
        this.themeColor = '1'
      }
    },
    
    // 设置主题色变量
    setThemeColorVariables(color) {
      const rgb = this.hexToRgb(color)
      const lightColor = this.lightenColor(color, 0.85)
      const glowColor = this.lightenColor(color, 0.20)
      
      // 设置CSS变量（兼容小程序和H5）
      // #ifdef H5
      if (typeof document !== 'undefined') {
        const root = document.documentElement
        root.style.setProperty('--primary-color', color)
        root.style.setProperty('--primary-color-light', lightColor)
        root.style.setProperty('--primary-color-glow', glowColor)
        root.style.setProperty('--primary-color-shadow', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`)
      }
      // #endif
      
      return {
        primaryColor: color,
        primaryColorLight: lightColor,
        primaryColorGlow: glowColor,
        primaryColorShadow: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`,
        backgroundGradient: `linear-gradient(135deg, ${lightColor} 0%, #F8F9FA 100%)`,
        cardShadow: `0 8rpx 32rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        cardBorder: `1rpx solid rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        replyBorderColor: color
      }
    },
    
    // 十六进制颜色转RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : { r: 74, g: 144, b: 226 }
    },
    
    // 颜色加深
    darkenColor(color, percent) {
      const rgb = this.hexToRgb(color)
      const factor = 1 - percent
      const r = Math.round(rgb.r * factor)
      const g = Math.round(rgb.g * factor)
      const b = Math.round(rgb.b * factor)
      return `rgb(${r}, ${g}, ${b})`
    },
    
    // 颜色变浅
    lightenColor(color, percent) {
      const rgb = this.hexToRgb(color)
      const factor = percent
      const r = Math.round(rgb.r + (255 - rgb.r) * factor)
      const g = Math.round(rgb.g + (255 - rgb.g) * factor)
      const b = Math.round(rgb.b + (255 - rgb.b) * factor)
      return `rgb(${r}, ${g}, ${b})`
    },

    // 开始浏览时长记录
    startBrowseTracking() {
      const token = getToken()
      const userInfo = getUserInfo()
      if (token && userInfo && userInfo.userId) {
        browseTracker.startTracking({
          pageType: 'comment_detail',
          pageName: '评论详情',
          pageUrl: '/pages/comment/detail',
          productId: this.productId,
          commentId: this.commentId
        }, userInfo.userId)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.comment-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
  
  .comment-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  }
  
  .comment-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20rpx;
    
    .user-info {
      .username {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .rating {
        display: flex;
        align-items: center;
        gap: 4rpx;
        
        .star {
          font-size: 24rpx;
          color: #ddd;
          
          &.active {
            color: #ffa500;
          }
        }
      }
    }
    
    .comment-time {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .comment-content {
    margin-bottom: 20rpx;
    
    .comment-text {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
    }
  }
  
  .comment-images {
    display: flex;
    gap: 10rpx;
    flex-wrap: wrap;
    margin-bottom: 20rpx;
    
    .comment-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      background: #f8f8f8;
    }
  }
  
  .merchant-reply {
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 20rpx;
    border-left: 4rpx solid var(--primary-color, #4A90E2);
    
    .reply-header {
      margin-bottom: 10rpx;
      
      .reply-label {
        font-size: 24rpx;
        color: var(--primary-color, #4A90E2);
        font-weight: 600;
      }
    }
    
    .reply-content {
      font-size: 26rpx;
      color: #666;
      line-height: 1.5;
    }
  }
  
  .product-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    
    .card-header {
      margin-bottom: 20rpx;
      
      .card-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
      }
    }
    
    .product-info {
      display: flex;
      align-items: center;
      
      .product-image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
        background: #f8f8f8;
      }
      
      .product-details {
        flex: 1;
        
        .product-name {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
          margin-bottom: 8rpx;
        }
        
        .product-price {
          font-size: 26rpx;
          color: var(--primary-color, #4A90E2);
          font-weight: 600;
        }
      }
    }
  }
  
  .loading-state, .empty-state {
    text-align: center;
    padding: 100rpx 0;
    
    .loading-text, .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }
}
</style>